/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * 获取年月日
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    return value.toString().padStart(2, "0");
  });
  return time_str;
}

/**
 * 获取具体时间
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (("" + time).length === 10) {
    time = parseInt(time) * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    );
  }
}

/**
 * 获取本月开始时间和结束时间
 */
export function getWeekStartAndEnd() {
  var firstDate = new Date();
  var startDate =
    firstDate.getFullYear() +
    "-" +
    (firstDate.getMonth() + 1 < 10 ? "0" : "") +
    (firstDate.getMonth() + 1) +
    "-" +
    "01";
  var date = new Date();
  var currentMonth = date.getMonth();
  var nextMonth = ++currentMonth;
  var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
  var oneDay = 1000 * 60 * 60 * 24;
  var lastDate = new Date(nextMonthFirstDay - oneDay);
  var endDate =
    lastDate.getFullYear() +
    "-" +
    (lastDate.getMonth() + 1 < 10 ? "0" : "") +
    (lastDate.getMonth() + 1) +
    "-" +
    (lastDate.getDate() < 10 ? "0" : "") +
    lastDate.getDate();

  return [startDate, endDate];
}

/**
 * 获取网址参数
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split("?")[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, " ") +
      '"}'
  );
}

/**
 * 分类递归
 */
export function recursion(data, type) {
  if (type) {
    data = [{ company_id: 0, id: 0, selfNext: [], title: "所有" }].concat(data);
  }
  data.map(e => {
    if (e.selfNext.length != 0) {
      categoryNext(e.selfNext);
    } else {
      e.selfNext = undefined;
    }
  });
  function categoryNext(arry) {
    arry.map(e => {
      if (e.selfNext.length != 0) {
        this.categoryNext(e.selfNext);
      } else {
        e.selfNext = undefined;
      }
    });
  }
  return data;
}

/**
 * 子分类判断
 */
export function category(data) {
  return data ? (data.length > 1 ? data[data.length - 1] : "") : "";
}

/* 
  导出封装
  res，后端请求来的文件流
  name，导出的文件名
*/
export function exportMethod(res, name) {
  console.log(res,name)
  let fileReader = new FileReader();
  fileReader.readAsText(res, "utf-8");
  fileReader.onload = function() {
    try {
      let jsonData = JSON.parse(this.result); // 说明是普通对象数据，后台转换失败+
      if (jsonData.errcode) {
        Message.error(jsonData.errmsg);
      }
    } catch (err) {
      const link = document.createElement("a");
      let blob = new Blob([res], {
        type:
          "application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      });
      link.style.display = "none";
      link.href = URL.createObjectURL(blob);
      link.download = name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  };
}


/**
 * 防抖
 */
export const Debounce = (fn, t) => {
  let delay = t || 500;
  let timer;
  return function() {
    let args = arguments;
    if (timer) {
      clearTimeout(timer);
    }

    let callNow = !timer;

    timer = setTimeout(() => {
      timer = null;
    }, delay);

    if (callNow) fn.apply(this, args);
  };
};
